﻿using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Web.UI.WebControls;
using HiTeachers.Entities;
using HiTeachers.Services;
using HiTeachers.Services.Exceptions;
using HiTeachers.Utilities;

namespace HiTeachers.Web
{
    public partial class Register : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack) return;

            BindingSubject(chklSubject);
            Page.CloseMessage(lblMsg);
        }

        protected void BtnSaveClick(object sender, EventArgs e)
        {
            Page.CloseMessage(lblMsg);
            lblMsgCapt.Visible = false;
            if (!Page.IsValid) return;

            captCode.ValidateCaptcha(txtCaptText.Text);
            if (!captCode.UserValidated)
            {
                lblMsgCapt.Visible = true;
                return;
            }

            string subjectes = chklSubject.Items.Cast<ListItem>().Where(item => item.Selected).Aggregate(string.Empty, (current, item) => current + (item.Value + ","));
            if (!string.IsNullOrEmpty(subjectes)) subjectes = subjectes.Substring(0, subjectes.Length - 1);

            try
            {
                var teacher = new Teacher
                              {
                                  Name = txtName.Text,
                                  Email = txtEmail.Text,
                                  Password = CryptorEngine.Encrypt(txtPassword.Text, CryptorEngine.EncryptKey, true),
                                  ActivatedDate = DateTime.Now.AddDays(-1),
                                  DeactivatedDate = DateTime.Now.AddDays(-1),
                                  PhoneNumber = txtPhoneNumber.Text,
                                  Address = txtAddress.Text,
                                  District = txtDistrict.Text,
                                  City = txtCity.Text,
                                  IsContactEmail = rdbEmail.Checked,
                                  IsReceiveNews = chkReceiveNews.Checked,
                                  Subject = subjectes,
                                  Intro = txtIntroduce.Text,
                                  IsFullAccount = false,
                                  UpdatedDate = DateTime.Now
                              };

                TeacherServices.SaveOrUpdate(teacher);
                if (fupPicture.HasFile)
                {
                    string pathFile = Server.MapPath("MemberImgs");
                    string fileName = string.Format("{0}{1}", teacher.ID, Path.GetExtension(fupPicture.FileName));
                    fupPicture.SaveAs(Path.Combine(pathFile, fileName));
                    string vtlPathFile = string.Format("/MemberImgs/{0}", fileName);

                    teacher.ImagePath = vtlPathFile;
                    TeacherServices.SaveOrUpdate(teacher);
                }

                SendActivationEmailAccount(teacher, txtPassword.Text);
                Page.DisplayMessage(lblMsg, "Đăng ký thành công! Vui lòng kiểm tra email của bạn để kích hoạt tài khoản.", MessageType.Success);
                ClearInputFields();
            }
            catch (EmailAlreadyLockException)
            {
                Page.DisplayMessage(lblMsg, string.Format("Email {0} đã bị ban!", txtEmail.Text), MessageType.Error);
            }
            catch (EmailAlreadyExistException)
            {
                Page.DisplayMessage(lblMsg, string.Format("Email {0} đã tồn tại!", txtEmail.Text), MessageType.Error);
            }
        }

        protected void BtnCancelClick(object sender, EventArgs e)
        {
            ClearInputFields();
        }

        #region Private Methods
        public void SendActivationEmailAccount(Teacher teacher, string password)
        {
            string tmpPath = Server.MapPath("mailtemplates");
            string mailCntPath = Path.Combine(tmpPath, "MailContents.xml");

            var dataSet = new DataSet();
            dataSet.ReadXml(mailCntPath);
            DataRow[] rows = dataSet.Tables["ActivationAccount"].Select();
            string subject = Convert.ToString(rows[0]["Subject"]);

            var urlActivate = string.Format("{0}/ActivationAccount.aspx?actid={1}", SiteUrl, teacher.ID);

            NVelocityBuilder.SetResourcePath(tmpPath);
            var contentMail = NVelocityBuilder.ActivationAccountEmailBuilder(Convert.ToString(rows[0]["Content"]), teacher.Name, urlActivate, teacher.Email, password);

            EmailSender.SendMail(subject, contentMail, teacher.Email);
        }

        private void ClearInputFields()
        {
            txtName.Text = string.Empty;
            txtEmail.Text = string.Empty;
            txtPassword.Text = string.Empty;
            txtPhoneNumber.Text = string.Empty;
            txtAddress.Text = string.Empty;
            txtDistrict.Text = string.Empty;
            txtCity.Text = string.Empty;
            txtIntroduce.Text = string.Empty;
            txtCaptText.Text = string.Empty;
        }
        #endregion


    }
}
